package cn.edu.henu.team.ui_login;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.Rotate;
import com.google.android.material.textfield.TextInputLayout;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.ninegrid.ImageInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.app.AlertDialog;
import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.base.BaseActivity;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.bean.collection;
import cn.edu.henu.team.bean.user_followers;
import cn.edu.henu.team.constant.ModelConstant;
import cn.edu.henu.team.utils.LocationUtils;
import cn.edu.henu.team.utils.myImageLoader;
import cn.edu.henu.team.utils.RegexUtils;
import de.hdodenhof.circleimageview.CircleImageView;

public class RegisterActivity extends BaseActivity {
    @BindView(R.id.header_img)
    CircleImageView headView;
    @BindView(R.id.register_et_username)
    TextInputLayout musername;
    @BindView(R.id.register_et_userphone)
    TextInputLayout muserphone;
    @BindView(R.id.register_et_password)
    EditText muserpwd;
    @BindView(R.id.register_et_rpassword)
    EditText muserrpwd;
    @BindView(R.id.register_et_age)
    TextInputLayout muserage;
    @BindView(R.id.register_et_sex)
    TextInputLayout musersex;
    @BindView(R.id.register_btn_register)
    Button usersign;
    @BindView(R.id.register_exit)
    TextView userexit;

    private EditText mEdtName, mEdtPhone, mEdtSex, mEdtAge;
    private String telephone,nickNameText,gender,age,passwordText, psw_againText,addressMsg;

    private double Longitude,Latitude;

    // Log打印的通用Tag
    private final String TAG = "RegisterActivity";

    String account = "";

    private static String imagePath = "";
    private ArrayList<ImageItem> imageItems;


    @Override
    protected int initLayout() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView() {
        // 全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    protected void initData() {
        LocationUtils.start(getApplicationContext(), new LocationUtils.onLocationListener() {
            @Override
            public void getData(AMapLocation aMapLocation) {
                addressMsg = aMapLocation.getCity()+" "+aMapLocation.getDistrict()+" "+aMapLocation.getStreet()+" "+aMapLocation.getStreetNum();
                Latitude = aMapLocation.getLatitude();
                Longitude = aMapLocation.getLongitude();
            }
        });

        Intent intent = getIntent();
        account = intent.getStringExtra("account");
        // 把对应的 account 设置到 telephone 输入框
        mEdtPhone = muserphone.getEditText();
        mEdtPhone.setText(account);
        mEdtName = musername.getEditText();
        mEdtSex = musersex.getEditText();
        mEdtAge = muserage.getEditText();
          /*
            设置当输入框焦点失去时提示错误信息
            第一个参数：输入框对象
            第二个参数：输入数据类型
            第三个参数：输入不合法时提示信息
         */
        setOnFocusChangeErrMsg(mEdtPhone, "phone", "手机号格式不正确");
        setOnFocusChangeErrMsg(muserpwd, "password", "密码不合法");
    }

    /**
     * 监听点击事件
     *
     * @param view
     */
    @OnClick({R.id.register_btn_register, R.id.register_exit,R.id.header_img})
    protected void onClick(View view) {

        telephone = mEdtPhone.getText().toString();
        nickNameText = mEdtName.getText().toString();
        gender = mEdtSex.getText().toString();
        age = mEdtAge.getText().toString();
        passwordText = muserpwd.getText().toString();
        psw_againText = muserrpwd.getText().toString();

        switch (view.getId()) {
            case R.id.register_btn_register:  //sign
                asyncRegister();
                break;
            case R.id.register_exit:  //返回登录界面
                startActivity(new Intent(mContext, LoginActivity.class));
                finish();
                break;
            case R.id.header_img:
                addHeaderImg();
                break;
            default:
                break;
        }
    }

    /*
    当输入账号FocusChange时，校验账号是否是中国大陆手机号
    当输入密码FocusChange时，校验密码是否不少于6位
     */
    private void setOnFocusChangeErrMsg(EditText editText, String inputType, String errMsg) {
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        String inputStr = editText.getText().toString();
                        // 失去焦点
                        if (!hasFocus) {
                            switch (inputType) {
                                case "phone":
                                    if (!RegexUtils.checkPhone(inputStr)) {
                                        editText.setError(errMsg);
                                    }
                                    break;
                                case "password":
                                    if (!RegexUtils.checkPassword(inputStr)) {
                                        editText.setError(errMsg);
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
        );
    }

    /**
     * 添加头像哦
     */
    private void addHeaderImg() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new myImageLoader());
        imagePicker.setMultiMode(false);   //多选
        imagePicker.setSelectLimit(1);    //最多选择X张
        imagePicker.setCrop(true);       //不进行裁剪
        Intent intent = new Intent(RegisterActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, 100);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String[] filePaths = new String[imageItems.size()];
                filePaths[0] = imageItems.get(0).path;
                imagePath = filePaths[0];
                Log.d("path",imagePath);
                Glide.with(RegisterActivity.this).load(imagePath).transform(new Rotate(0)).into(headView);
            } else {
               showToastInThread(getApplicationContext(),"没有选择图片呢! ");
            }
        }
    }

    /**
     *异步登录
     */
    public void asyncRegister(){
        if (nickNameText.equals("") || telephone.equals("") || passwordText.equals("") || psw_againText.equals("") || gender.equals("") || age.equals(""))
            Toast.makeText(getApplication(), "请填写完整", Toast.LENGTH_SHORT).show();
        else if (imagePath.equals(""))
            Toast.makeText(getApplication(), "请上传你喜欢的头像", Toast.LENGTH_SHORT).show();
        else if (!passwordText.equals(psw_againText))
            Toast.makeText(getApplication(), "请注意：您的两次密码填写不一致", Toast.LENGTH_SHORT).show();
        else {
            uploadImage_then_signUp();
        }
    }

    /**
     * 将图片上传到 Bmob
     */
    public void uploadImage_then_signUp() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(true);
        progressDialog.setMessage("正在注册中...");
        progressDialog.show();
        Log.e("img", imagePath);
        final String icon_path;
        icon_path = imagePath;
        Integer age1 = Integer.parseInt(age);
        Integer sex1 = Integer.parseInt(gender);

        final BmobFile file = new BmobFile(new File(icon_path));
        file.uploadblock(new UploadFileListener() {         //上传文件
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    //TODO 在实际应用中，此处利用实时定位替换为真实经纬度数据
                    final BmobGeoPoint bmobGeoPoint = new BmobGeoPoint(Longitude, Latitude);
                    // 图片上传成功后注册用户
                    _User user = new _User();
                    user.setheadPortrait(file);
                    user.setAge(age1);
                    user.setAddressMsg(addressMsg);
                    user.setAddress(bmobGeoPoint);
                    user.setSex(sex1);
                    user.setImg_url(icon_path);
                    user.setNickName(nickNameText);
                    user.setMobilePhoneNumber(telephone);
                    user.setPassword(passwordText);
                    user.setUsername(telephone);//把username与telephone归为一类
                    user.setFocusId_sum(0);
                    user.signUp(new SaveListener<_User>() {      //用户注册
                        @Override
                        public void done(_User s, BmobException e) {
                            if (e == null) {
                                _User user = new _User();
                                user.setUsername(telephone);
                                user.setPassword(passwordText);
                                user.login(new SaveListener<_User>() {  //用户注册后自动登录
                                    @Override
                                    public void done(_User s, BmobException e) {
                                        if (e == null) {
                                            // 注册成功，建立对应的user_followers(粉丝)数据
                                            user_followers this_user_followers = new user_followers();
                                            this_user_followers.setUser_id(s.getObjectId());
                                            this_user_followers.setUser(BmobUser.getCurrentUser(_User.class));
                                            this_user_followers.save(new SaveListener<String>() {
                                                @Override
                                                public void done(String id, BmobException e) {
                                                    if (e == null) {
                                                        user_followers temp = new user_followers(); //一个用户对应一张粉丝表
                                                        temp.setObjectId(id);   //保存成功返回记录的id值
                                                        _User u = BmobUser.getCurrentUser(_User.class);
                                                        u.setFollower_id(temp);// 添加一对一关联
                                                        u.update(new UpdateListener() {
                                                            @Override
                                                            public void done(BmobException e) {
                                                                if (e == null) {
                                                                    //Toast.makeText(getApplication(), "关联成功", Toast.LENGTH_SHORT).show();
                                                                } else {
                                                                    //Toast.makeText(getApplication(), "关联失败", Toast.LENGTH_SHORT).show();
                                                                }
                                                            }
                                                        });
                                                        //Toast.makeText(getApplication(), "创建成功", Toast.LENGTH_SHORT).show();
                                                    } else {
                                                        //Toast.makeText(getApplication(), "创建失败", Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            });

                                            // 新建默认收藏夹
                                            collection this_collection = new collection();
                                            this_collection.setUserOnlyId(s.getObjectId());
                                            this_collection.setName("默认收藏夹");
                                            this_collection.setIntroduction("将你学到的病理知识添加至此类别的收藏夹之中吧~");
                                            this_collection.setImage(file);
                                            this_collection.setPublicOrNot(true);
                                            this_collection.save(new SaveListener<String>() {
                                                @Override
                                                public void done(String s, BmobException e) {
                                                    if (e == null) {
                                                        collection tempp = new collection();
                                                        tempp.setObjectId(s);
                                                        BmobRelation relation = new BmobRelation();
                                                        relation.add(tempp);
                                                        _User uu = BmobUser.getCurrentUser(_User.class);
                                                        uu.setMyCollection(relation);// 添加一对多关联
                                                        uu.update(new UpdateListener() {
                                                            @Override
                                                            public void done(BmobException e) {
                                                                if (e == null) {
                                                                    //Toast.makeText(getApplication(), "关联成功", Toast.LENGTH_SHORT).show();
                                                                } else {
                                                                    //Toast.makeText(getApplication(), "关联失败", Toast.LENGTH_SHORT).show();
                                                                }
                                                            }
                                                        });
                                                        //Toast.makeText(getApplication(), "创建成功", Toast.LENGTH_SHORT).show();
                                                    } else {
                                                        //Toast.makeText(getApplication(), "创建失败", Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            });

                                            // 将官方账号列入关注列表里
                                            _User office = new _User();
                                            office.setObjectId("4cc0024747");
                                            // 添加到多对多关联中
                                            BmobRelation relation = new BmobRelation();
                                            relation.add(office);
                                            s.setFocusId(relation);
                                            s.increment("focusId_sum");//关注人数自增1
                                            s.update(new UpdateListener() {
                                                @Override
                                                public void done(BmobException e) {
                                                    if(e==null){
                                                        //Toast.makeText(getApplication(), "关联成功", Toast.LENGTH_SHORT).show();
                                                    }else{
                                                        //Toast.makeText(getApplication(), "关联失败", Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            });

                                            // 官方账号的粉丝列表、人数发生相应改变
                                            final BmobRelation relation_2 = new BmobRelation();
                                            relation_2.add(s);

                                            BmobQuery<user_followers> query = new BmobQuery<user_followers>();
                                            query.addWhereEqualTo("user_id", "4cc0024747");
                                            query.findObjects(new FindListener<user_followers>() {
                                                @Override
                                                public void done(List<user_followers> list, BmobException e) {
                                                    if (e == null) {
                                                        if (list.size() == 1) {
                                                            user_followers the_user_followers = new user_followers();
                                                            the_user_followers.setFollowerId(relation_2);
                                                            the_user_followers.increment("follower_sum");
                                                            the_user_followers.increment("message_fans_sum");
                                                            the_user_followers.increment("message_fans_read",0);
                                                            the_user_followers.increment("message_sayings_read",0);
                                                            the_user_followers.increment("message_sayings_sum",0);
                                                            the_user_followers.update(list.get(0).getObjectId(), new UpdateListener() {
                                                                @Override
                                                                public void done(BmobException ee) {
                                                                    if(ee==null){
                                                                        //Toast.makeText(getApplication(), "关联成功", Toast.LENGTH_SHORT).show();
                                                                    }else{
                                                                        //Toast.makeText(getApplication(), "关联失败" + ee.getMessage(), Toast.LENGTH_SHORT).show();
                                                                    }
                                                                }
                                                            });
                                                        }
                                                    } else {
                                                        //Toast.makeText(getApplication(), "失败: "+e.getMessage(), Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            });
                                        } else {
                                            //Toast.makeText(getApplication(), "关联失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                                createDialog();
                                progressDialog.dismiss();
                            } else {
                                if (e.getErrorCode() == 202 || e.getErrorCode() == 203) {
                                    Toast.makeText(getApplication(), "抱歉，该手机号已被注册", Toast.LENGTH_SHORT).show();
                                    progressDialog.dismiss();
                                }
                                else if (e.getErrorCode() == 301) {
                                    Toast.makeText(getApplication(), "手机号格式必须填写规范", Toast.LENGTH_SHORT).show();
                                    progressDialog.dismiss();
                                }
                                else {
                                    Toast.makeText(getApplication(), "注册失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                    progressDialog.dismiss();
                                }
                            }
                        }
                    });
                } else {
                    Toast.makeText(getApplication(), "图片上传失败", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
            }
        });
    }
    /**
     *注册成功弹出确定对话框
     */
    public void createDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setMessage("注册成功！尝试登录吧")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        insertVal(ModelConstant.LOGIN_INFO,"telephone",telephone);
                        insertVal(ModelConstant.LOGIN_INFO,"password",passwordText);
                        startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create();
        alertDialog.show();
    }
}